package com.leyou.seckill.service;

import com.leyou.common.utils.JsonUtils;
import com.leyou.seckill.dto.SeckillPolicyDTO;
import com.leyou.seckill.entity.TbSeckillPolicy;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class SeckillRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String seckill_prefix ="seckill:goods:";
    private String seckill_num_prefix ="seckill:goods:num";

    public void saveSeckillToRedis(TbSeckillPolicy tbSeckillPolicy){
        Long seckillId = tbSeckillPolicy.getId();
        redisTemplate.boundValueOps(seckill_prefix+seckillId).set(JsonUtils.toString(tbSeckillPolicy));

//        保存redis队列 为了判断库存
        Integer stockCount = tbSeckillPolicy.getStockCount();
        for (int i = 0; i < stockCount; i++) {
            redisTemplate.boundListOps(seckill_num_prefix+seckillId).rightPush(seckillId.toString());
        }
    }


    public void removeSeckillFromRedis(Long seckillId){

        redisTemplate.delete(seckill_prefix+seckillId);

        redisTemplate.delete(seckill_num_prefix+seckillId);
    }

    // 判断时间
    public Boolean judgeTime(Long seckillId) {
//        开始时间 <=   当前时间  <=   结束时间
        String str = redisTemplate.boundValueOps(seckill_prefix + seckillId).get();
        TbSeckillPolicy seckillPolicy = JsonUtils.toBean(str, TbSeckillPolicy.class);
        long beginTime = seckillPolicy.getBeginTime().getTime();  //获取开始时间的毫秒值
        long nowTime = DateTime.now().getMillis();                //获取当前时间的毫秒值
        long endTime = seckillPolicy.getEndTime().getTime();     //获取结束时间的毫秒值
        if(nowTime-beginTime>=0 && endTime-nowTime>=0){
            return true;
        }
        return false;
    }

    //判断库存
    public Boolean judgeStockCount(Long seckillId) {
        String s = redisTemplate.boundListOps(seckill_num_prefix + seckillId).leftPop();
        if(StringUtils.isNotBlank(s)){ //有数据
            return true;
        }
       return false;
    }
}
